package org.openems;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.openems.entity.Entity;
import org.openems.entity.ParameterConverter;
import org.openems.entity.TraceEntity;
import org.openems.meta.ParameterModelMeta;
import org.openems.model.ParameterModel;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.KeyFactory;

@Path("/trace")
public class TraceResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public PrimitiveTraceEntity get(@QueryParam("key") String key, @QueryParam("points") String points) {
        ParameterModel model = Datastore.get(ParameterModel.class, KeyFactory.stringToKey(key));
        TraceEntity entity = (TraceEntity)new ParameterConverter().get(model.getBlob().getBytes());
      
        PrimitiveTraceEntity ret = new PrimitiveTraceEntity();
        Double[] trace = entity.getData();
        int max = Integer.valueOf(points);
        double step = (double)trace.length / (double)max;
        for (double i = 0; i < trace.length; i += step) {
            ret.y.add(trace[(int)i]);
        }
        
        ret.key = key;
        ret.horizontalMax = (double)ret.y.size();
        ret.horizontalMin = 0.0;
  
        return ret;
    }

    private ParameterModel getTestModel() {
        ParameterModelMeta e = ParameterModelMeta.get();
        for (ParameterModel model : Datastore.query(e).asList()) {
            Entity entity = new ParameterConverter().get(model.getBlob().getBytes());
            if (entity instanceof TraceEntity) {
                return model;
            }
        }
        return null;
    }
}
